<template>
  <div class="p-2">

    <div class="mb-[10px]">
      <el-card>
        <el-form
          ref="queryFormRef"
          :model="queryParams"
          :inline="true"
          label-width="auto"
        >
          <el-form-item
            label="业务类型"
            prop="busType"
          >
            <el-select
              v-model="queryParams.busType"
              placeholder="请选择业务类型"
              style="width: 160px"
              clearable
              filterable
            >
              <el-option
                v-for="(item,i) in wxfe_bus_type"
                :label="item.label"
                :value="item.value"
                :key="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="产品编号"
            prop="no"
          >
            <el-input
              v-model="queryParams.no"
              placeholder="请输入产品编号"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item
            label="计费模式"
            prop="chargeMode"
          >
            <el-select
              v-model="queryParams.chargeMode"
              placeholder="请选择计费模式"
              style="width: 160px"
              clearable
              filterable
            >
              <el-option
                v-for="(item,i) in charge_mode"
                :label="item.label"
                :value="item.value"
                :key="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="结算方式"
            prop="settlementStyle"
          >
            <el-select
              v-model="queryParams.settlementStyle"
              placeholder="请选择结算方式"
              style="width: 160px"
              clearable
              filterable
            >
              <el-option
                v-for="(item,i) in settlement_style"
                :label="item.label"
                :value="item.value"
                :key="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              @click="handleQuery"
              icon="Search"
            >查询</el-button>
            <el-button
              @click="resetQuery"
              icon="Refresh"
            >重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    <el-card>
      <template #header>
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-button
              type="primary"
              @click="addAndEditDialogFun('新增')"
              icon="Plus"
            >新增</el-button>
          </el-col>
        </el-row>
      </template>
      <el-table
        v-loading="loading"
        :data="productManagementList"
        border
      >
        <el-table-column
          label="产品编号"
          align="center"
          min-width="160"
          prop="no"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="服务商编号"
          align="center"
          min-width="160"
          prop="sydNo"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="服务商名称"
          align="center"
          min-width="160"
          prop="sydName"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="成本费率"
          align="center"
          min-width="160"
          prop="serviceCharge"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="平台费率"
          align="center"
          min-width="160"
          prop="setingServiceCharge"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="计费模式"
          align="center"
          min-width="160"
          prop="chargeMode"
          :show-overflow-tooltip="true"
        >
          <template #default="scope">
            <dict-tag
              :options="charge_mode"
              :value="scope.row.chargeMode"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="到账方式"
          align="center"
          min-width="160"
          prop="settlementStyle"
          :show-overflow-tooltip="true"
        >
          <template #default="scope">
            <dict-tag
              :options="settlement_style"
              :value="scope.row.settlementStyle"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="单月发放上限（元）"
          align="center"
          min-width="160"
          prop="maxMonth"
          :show-overflow-tooltip="true"
        >
          <template #default="scope">
            {{ convertFenToYuan(scope.row.maxMonth) }}
          </template>
        </el-table-column>
        <el-table-column
          label="发票类型"
          align="center"
          min-width="160"
          prop="invoiceType"
          :show-overflow-tooltip="true"
        >
          <template #default="scope">
            <dict-tag
              :options="invoice_type"
              :value="scope.row.invoiceType"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="状态"
          align="center"
          min-width="160"
          prop="proStatus"
          :show-overflow-tooltip="true"
        >
          <template #default="scope">
            <dict-tag
              :options="pro_status"
              :value="scope.row.proStatus"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="开票类目"
          align="center"
          min-width="160"
          prop="invoiceItems"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="操作"
          fixed="right"
          align="center"
          width="210"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-tag
              link
              type="primary"
              @click="addAndEditDialogFun('编辑', scope.row)"
            >编辑</el-tag>
            <el-tag
              link
              type="primary"
              @click="addAndEditDialogFun('详情', scope.row)"
            >详情</el-tag>

            <el-tag
              link
              type="primary"
              v-if="scope.row.proStatus == 2"
              @click="upDown('上架', scope.row)"
            >上架</el-tag>

            <el-tag
              link
              type="primary"
               v-if="scope.row.proStatus == 1"
              @click="upDown('下架', scope.row)"
            >下架</el-tag>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    <el-dialog
      :title="dialogTitle"
      v-model="addAndEditDialogVisible"
      width="70%"
      append-to-body
      @close="dialogClose"
    >
      <el-form
        ref="dialogFormRef"
        :model="dialogForm"
        :rules="dialogRules"
        label-width="auto"
        :disabled="dialogTitle=='详情'"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item
              label="业务类型"
              prop="busType"
            >
              <el-select
                v-model="dialogForm.busType"
                placeholder="请选择业务类型"
                clearable
                filterable
                style="width: 100%;"
              >
                <el-option
                  v-for="(item,i) in wxfe_bus_type"
                  :label="item.label"
                  :value="item.value"
                  :key="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="成本费率(%)"
              prop="serviceCharge"
            >
              <el-input
                v-model="dialogForm.serviceCharge"
                placeholder="请输入成本费率"
                type="number"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="平台费率(%)"
              prop="setingServiceCharge"
            >
              <el-input
                v-model="dialogForm.serviceCharge"
                placeholder="请输入平台费率"
                type="number"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="计费模式"
              prop="chargeMode"
            >
              <el-select
                v-model="dialogForm.chargeMode"
                placeholder="请选择计费模式"
                clearable
                style="width: 100%;"
              >
                <el-option
                  v-for="(item,i) in charge_mode"
                  :label="item.label"
                  :value="item.value"
                  :key="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="结算方式"
              prop="settlementStyle"
            >
              <el-select
                v-model="dialogForm.settlementStyle"
                placeholder="请选择结算方式"
                clearable
                style="width: 100%;"
              >
                <el-option
                  v-for="(item,i) in settlement_style"
                  :label="item.label"
                  :value="item.value"
                  :key="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="单月发放上限（元）"
              prop="maxMonth"
            >
              <el-input
                v-model="dialogForm.maxMonth"
                placeholder="请输入单月发放上限（元）"
                type="number"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="开票类型"
              prop="invoiceType"
            >
              <el-select
                v-model="dialogForm.invoiceType"
                placeholder="请选择开票类型"
                clearable
                filterable
                style="width: 100%;"
              >
                <el-option
                  v-for="(item,i) in invoice_type"
                  :label="item.label"
                  :value="item.value"
                  :key="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="开票类目"
              prop="invoiceItemList"
            >
             <el-cascader ref="cascaderRef" :options="invoiceItemData" :props="props1"  v-model="dialogForm.invoiceItemList"
                placeholder="请选择开票类目" clearable  :show-all-levels="false" :collapse-tags="true"/>
             <!--  <el-select
                v-model="dialogForm.invoiceItemList"
                placeholder="请选择开票类目"
                clearable
                filterable
                multiple
                invoiceItemData
                style="width: 100%;"
              >
                <el-option
                  v-for="(item,i) in invoiceItemData"
                  :label="item.type"
                  :value="item"
                  :key="item.value"
                />
              </el-select> -->
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="dialogTitle!='详情'"
            type="primary"
            @click="submitForm"
          >确 定</el-button>
          <el-button @click="addAndEditDialogVisible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="productManagement" lang="ts">
import api from '@/api/service/addService';
import { AddAndEditForm, InvoiceItemList, ProductManagementQuery, ProductManagementVO } from '@/api/service/addService/types';

const router = useRouter();
const route = useRoute();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const props = defineProps({
  sydNo: {
    type: String,
    default: ''
  }
});
const { wxfe_bus_type, invoice_type, charge_mode, settlement_style, mer_invoice_type ,pro_status} = toRefs<any>(
  proxy?.useDict('wxfe_bus_type', 'invoice_type', 'charge_mode', 'settlement_style', 'mer_invoice_type', 'pro_status')
);

const props1= ref({ multiple: true,emitPath:false })
const productManagementList = ref<ProductManagementVO[]>();
const loading = ref(true);
const total = ref(0);
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
const queryFormRef = ref<ElFormInstance>();
const queryParams = ref<ProductManagementQuery>({
  pageNum: 1,
  pageSize: 10,
  params:{
    syd_no:''
  },
  busType: '',
  no: '',
  chargeMode: '',
  settlementStyle: ''
});

/** 查询代理商列表 */
const getList = async () => {
  loading.value = true;
  const res = await api.productManagementList(proxy?.addDateRange(queryParams.value, dateRange.value));
  loading.value = false;
  productManagementList.value = res.rows;
  total.value = res.total;
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  queryFormRef.value?.resetFields();
  queryParams.value.pageNum = 1;
  handleQuery();
};



/** 新增&修改 */
const addAndEditDialogVisible = ref<boolean>(false);
const dialogTitle = ref<string>('新增');
const dialogFormRef = ref<any>();
const dialogForm = ref<AddAndEditForm>({
  busType: '',
  serviceCharge: '',
  setingServiceCharge: '',
  chargeMode: '',
  settlementStyle: '',
  maxMonth: '',
  invoiceType: '',
  invoiceItemList: []
});


const serviceChargeValidator = (rule: any, value: any, callback: any) => {
  if (dialogForm.value.serviceCharge > value) {
    callback(new Error("平台费率不能小于成本费率"));
  } else {
    callback();
  }
}

const commonValidator = (rule: any, value: any, callback: any) => {
  if (value <= 0 || value >= 100) {
    callback(new Error("费率不能小于0,大于100"));
  } else {
    callback();
  }
}


const maxMonthValidator = (rule: any, value: any, callback: any) => {
  if (value <= 0) {
    callback(new Error("单月发放上限需大于0"));
  } else {
    callback();
  }
};


const dialogRules = ref({
  busType: [{ required: true, message: '请选择业务类型', trigger: 'blur' }],
  serviceCharge: [{ required: true, message: '请输入成本费率', trigger: 'blur' }, {
    required: true,
    validator: commonValidator,
    trigger: "blur"
  }],
  // setingServiceCharge: [{ required: true, message: '请输入平台费率', trigger: 'blur' }, {
  //   required: true,
  //   validator: serviceChargeValidator,
  //   trigger: "blur"
  // }, {
  //   required: true,
  //   validator: commonValidator,
  //   trigger: "blur"
  // }],
  chargeMode: [{ required: true, message: '请选择计费模式', trigger: 'blur' }],
  settlementStyle: [{ required: true, message: '请选择结算方式', trigger: 'blur' }],
  maxMonth: [{ required: true, message: '请输入单月发放上限（元）', trigger: 'blur' }, {
    required: true,
    validator: maxMonthValidator,
    trigger: "blur"
  }],
  invoiceType: [{ required: true, message: '请选择开票类型', trigger: 'blur' }],
  invoiceItemList: [{ required: true, message: '请选择开票类目', trigger: 'blur' }]
});
const invoiceItemData = ref<any>();
const getInvoiceIds = (invoiceIds)=>{

  return invoiceIds.map(item=>{
    return parseInt(item);
  })
}

const upDown = async(type:string,row:any)=>{

 const ress = await api.productUpDown({
   id:row.id,
   status:type == '上架'?1:2
 });
  proxy?.$modal.msgSuccess('操作成功');
  getList();
}

const addAndEditDialogFun = async (type: string, row: any = '') => {
  addAndEditDialogVisible.value = true;
  dialogTitle.value = type;
  if (type != '新增') {
    const res = await api.productManagementDetail(row.id);
    dialogForm.value = res.data;
    dialogForm.value.busType = res.data.busType+"";
    dialogForm.value.chargeMode = res.data.chargeMode+"";
    dialogForm.value.settlementStyle = res.data.settlementStyle+"";
    dialogForm.value.invoiceType = res.data.invoiceType+"";
    dialogForm.value.invoiceItemList = res.data.invoiceIds?getInvoiceIds(res.data.invoiceIds.split(",")):[];
    console.log(dialogForm.value.invoiceItemList);
    (dialogForm.value.maxMonth as any) = proxy?.convertFenToYuan(res.data.maxMonth);
  }
  const ress = await api.getInvoiceList();
  invoiceItemData.value = ress.data;
  console.log(ress);
};
const cascaderRef = ref()
const submitForm = () => {
  dialogFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      let arr = [];
      console.log(dialogForm.value);
      let selNodes = cascaderRef.value.getCheckedNodes(true);
      console.log(selNodes);
      let invoces = [];
      let invoceIds = [];
      let invoceNames = [] ;
      if(selNodes){
        selNodes.forEach(item=>{
          invoceIds.push(item.data.value);
          invoceNames.push(item.data.label);
            arr.push({
              invoiceTypeId:item.data.value,
              invoiceTypeName:item.data.label
            });
        })
      }
      // dialogForm.value.invoiceItemList.forEach((e) => {
      //   arr.push({
      //     invoiceTypeId: e.id,
      //     invoiceTypeName: e.type
      //   });
      // });
      let obj = {
        ...dialogForm.value,
        invoiceItemList: arr,
        invoiceIds:invoceIds.join(","),
        invoiceItems:invoceNames.join(","),
        setingServiceCharge:dialogForm.value.serviceCharge,
        sydId:sydId.value,
        sydNo:sydNo.value,
        maxMonth: (dialogForm.value.maxMonth as any) * 100
      };
  console.log(obj);
      let res = await api.addOrEditProductManagement(obj, obj.id ? 'put' : 'post');
      console.log(res);
      getList();
      proxy?.$modal.msgSuccess(res.msg);
      addAndEditDialogVisible.value = false;
    }
  });
};
const dialogClose = () => {
  dialogFormRef.value.resetFields();
  dialogForm.value = {
    busType: '',
    serviceCharge: '',
    setingServiceCharge: '',
    chargeMode: '',
    settlementStyle: '',
    maxMonth: '',
    invoiceType: '',
    invoiceItemList: []
  };
  addAndEditDialogVisible.value = false;
  dialogTitle.value = '';
};
const sydNo = ref();
const sydId = ref();

onMounted(() => {
  if (route.query.sydNo) {
    queryParams.value.params.syd_no = route.query.sydNo;
    sydNo.value = route.query.sydNo;
    sydId.value = route.query.sydId;

  }

  getList(); // 初始化列表数据
});
</script>

<style lang="scss" scoped></style>
